package com.yusp75.myexam.ui.browse

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.yusp75.myexam.R
import com.yusp75.myexam.com.yusp75.myexam.ui.browse.BrowseAdapter
import com.yusp75.myexam.com.yusp75.myexam.data.QuestionFilter
import com.yusp75.myexam.databinding.FragmentBrowseBinding
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel

class BrowseFragment : Fragment() {

    private var _binding: FragmentBrowseBinding? = null
    private val binding get() = _binding!!
    private val viewModel: BrowseViewModel by viewModel()

    private lateinit var m_adapter: BrowseAdapter
    private val handler = Handler(Looper.getMainLooper())


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentBrowseBinding.inflate(inflater, container, false)
        val root: View = binding.root

        m_adapter = BrowseAdapter(viewModel, viewLifecycleOwner)
        binding.rvQuestions.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = m_adapter
        }

        loadData()
        //
        return root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 标记已会
        viewModel.deleteResult.observe(viewLifecycleOwner) { success ->
            // 处理删除结果
            loadData()
        }
        // filter
        aboutFilter()
        loadData()
        //
    }

    private fun aboutFilter() {
        // 类型筛选
        // 1
        binding.filter.setOnCheckedChangeListener { _, checkedId ->
            viewModel.setFilter(
                when (checkedId) {
                    R.id.question_all -> QuestionFilter.ALL
                    R.id.question_favorite -> QuestionFilter.FAVORITE
                    R.id.question_only_wrong -> QuestionFilter.ONLYWRONG
                    else -> return@setOnCheckedChangeListener // 处理未匹配情况
                }
            )
        }

        // 2
        when (viewModel.getFilter()) {
            QuestionFilter.ALL -> binding.questionAll.isChecked = true
            QuestionFilter.FAVORITE -> binding.questionFavorite.isChecked = true
            QuestionFilter.ONLYWRONG -> binding.questionOnlyWrong.isChecked = true
        }

    }

    private fun loadData() {
        // 更新数据
        lifecycleScope.launch {
            viewModel.pagedData.collectLatest { data ->
                m_adapter.submitData(data)
            }
        }

        // 数据加载状态
        m_adapter.addLoadStateListener { state ->
            println("adapter当前数: ${m_adapter.itemCount}")
            println("adapter状态: ${state.refresh}")
        }

    }

    override fun onDestroyView() {
        super.onDestroyView()

        viewModel.saveFilter()
        _binding = null
    }
}